package com.dc.web.controller;


import com.dc.constant.MessageConstant;
import com.dc.dao.*;
import com.dc.entity.*;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.WorkflowListBody;
import com.dc.service.CalibrationService;
import com.dc.service.dto.CalibrationPaintHouseDto;
import com.dc.utils.DateUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Api(tags = "6-1-涂装喷漆-喷漆房分段喷漆-单船")
@RequestMapping("/api/workflow_paint_house")
@RestController
public class WorkflowPaintHouseController {

    @Resource
    WorkflowPaintHouseDao workflowPaintHouseDao;

    @Resource
    WorkflowPaintHouseChildDao workflowPaintHouseChildDao;

    @Resource
    ShipRepairDao shipRepairDao;

    @Resource
    ShipDao shipDao;

    @Resource
    CalibrationService calibrationService;

    @GetMapping("/list")
    public AjaxResult list(WorkflowListBody body) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Long repairId = body.getRepairId();     // 维修工单id

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(repairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        Page<WorkflowPaintHouseEntity> resultList = workflowPaintHouseDao.findByShipRepairEntity(shipRepairEntity, pageRequest);

        CalibrationPaintHouseDto calibrationPaintHouseDto = calibrationService.calcPaintHouse();

        resultList.getContent().forEach(t -> {
            dynamicCalc(t, shipEntity, shipRepairEntity, calibrationPaintHouseDto);
        });

        return AjaxResult.success(resultList);
    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<WorkflowPaintHouseEntity> optional = workflowPaintHouseDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowPaintHouseEntity shipOilEntity = optional.get();

        ShipRepairEntity shipRepairEntity = shipOilEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);

        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        CalibrationPaintHouseDto calibrationPaintHouseDto = calibrationService.calcPaintHouse();

        dynamicCalc(shipOilEntity, shipEntity, shipRepairEntity, calibrationPaintHouseDto);

        return AjaxResult.success(shipOilEntity);
    }


    //  shipRepairId   weight   shipWeight    submit_time
    @PostMapping()
    public AjaxResult add(@RequestHeader HttpHeaders httpHeaders, @RequestBody WorkflowPaintHouseEntity entity) {

        entity.setId(null);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);
        entity.setSubmitTime(new Date());

        WorkflowPaintHouseEntity save = workflowPaintHouseDao.save(entity);

        CalibrationPaintHouseDto calibrationPaintHouseDto = calibrationService.calcPaintHouse();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationPaintHouseDto);

        return AjaxResult.success(save);
    }

    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody WorkflowPaintHouseEntity entity) {

        Optional<WorkflowPaintHouseEntity> optionalPaintHouse = workflowPaintHouseDao.findById(id);
        if(!optionalPaintHouse.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowPaintHouseEntity houseEntity = optionalPaintHouse.get();

        ShipRepairEntity shipRepairEntity = houseEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        //////////////////////// 设置字段
        houseEntity.setProject(entity.getProject());
        houseEntity.setArea(entity.getArea());
        houseEntity.setRoom(entity.getRoom());
        houseEntity.setSubmitTime(new Date());

        WorkflowPaintHouseEntity save = workflowPaintHouseDao.save(houseEntity);

        CalibrationPaintHouseDto calibrationPaintHouseDto = calibrationService.calcPaintHouse();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationPaintHouseDto);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        workflowPaintHouseDao.deleteById(id);

        return AjaxResult.success();
    }

    /////////////////////////////////////////////////// child
    @GetMapping("/child/{id}")
    public AjaxResult showChild(@PathVariable("id") Long id) {
        Optional<WorkflowPaintHouseChildEntity> optional = workflowPaintHouseChildDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowPaintHouseChildEntity houseChildEntity = optional.get();

        houseChildEntity.setPid(houseChildEntity.getWorkflowPaintHouseEntity().getId());

        return AjaxResult.success(houseChildEntity);
    }

    @PostMapping("/child")
    public AjaxResult addChild(@RequestBody WorkflowPaintHouseChildEntity entity) {

        entity.setId(null); // 新增保证 id = null，避免变成更新

        Optional<WorkflowPaintHouseEntity> optionalPainHouse = workflowPaintHouseDao.findById(entity.getPid());
        if(!optionalPainHouse.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowPaintHouseEntity houseEntity = optionalPainHouse.get();

        entity.setWorkflowPaintHouseEntity(houseEntity);
        // 动态计算子
        calcChild(entity);

        WorkflowPaintHouseChildEntity save = workflowPaintHouseChildDao.save(entity);

        return AjaxResult.success(save);
    }

    @PutMapping("/child/{id}")
    public AjaxResult updateChild(@PathVariable("id") Long id, @RequestBody WorkflowPaintHouseChildEntity entity) {

        entity.setId(id); // 新增保证 id = null，避免变成更新

        Optional<WorkflowPaintHouseEntity> optionalPainHouse = workflowPaintHouseDao.findById(entity.getPid());
        if(!optionalPainHouse.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowPaintHouseEntity houseEntity = optionalPainHouse.get();

        entity.setWorkflowPaintHouseEntity(houseEntity);
        // 动态计算子
        calcChild(entity);

        WorkflowPaintHouseChildEntity save = workflowPaintHouseChildDao.save(entity);

        save.setPid(houseEntity.getId());

        return AjaxResult.success(save);
    }

    @DeleteMapping("/child/{id}")
    public AjaxResult deleteChild(@PathVariable("id") Long id) {
        Optional<WorkflowPaintHouseChildEntity> childEntityOptional = workflowPaintHouseChildDao.findById(id);
        if(!childEntityOptional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_CALIBRATION_MISSION);
        }

        WorkflowPaintHouseChildEntity childEntity = childEntityOptional.get();

        WorkflowPaintHouseEntity workflowPaintHouseEntity = childEntity.getWorkflowPaintHouseEntity();
        workflowPaintHouseEntity.getInner().remove(childEntity);

        workflowPaintHouseDao.save(workflowPaintHouseEntity);


        workflowPaintHouseChildDao.deleteById(id);

        return AjaxResult.success();
    }

    /////////////////////////////////////////////////  动态计算

    /**
     * 计算动态值
     * @param entity
     * @param shipEntity
     * @param shipRepairEntity
     */

    public static WorkflowPaintHouseEntity dynamicCalc(WorkflowPaintHouseEntity entity,
                                                ShipEntity shipEntity,
                                                ShipRepairEntity shipRepairEntity,
                                                CalibrationPaintHouseDto calibrationPaintHouseDto) {

        Double paintHouseAirByUnit = calibrationPaintHouseDto.getPaintHouseAirByUnit();

        Double paintHouseGasByUnit = calibrationPaintHouseDto.getPaintHouseGasByUnit();

        // 单位耗天然气量标定值
        entity.gasByUnit = paintHouseGasByUnit;

        // 天然气
        entity.gas = paintHouseGasByUnit * entity.getArea();

        // 单位耗压缩空气量标定值
        entity.airByUnit = paintHouseAirByUnit;

        // 空气
        entity.air = paintHouseAirByUnit * entity.getArea();

        // 总电量， 子表求和
        List<WorkflowPaintHouseChildEntity> inner = entity.getInner();
        double sum = inner.stream().mapToDouble(WorkflowPaintHouseChildEntity::getTotalPower).sum();

        inner.forEach(t->t.setPid(entity.getId()));

        entity.setPowers(sum);

        ///////////////////////////////////////////////////
        entity.setShipName(shipEntity.getName());
        entity.setReporter(shipRepairEntity.getUpdater());
        entity.setShipRepairId(shipRepairEntity.getId());
        return entity;
    }

    private WorkflowPaintHouseChildEntity calcChild(WorkflowPaintHouseChildEntity entity) {

        try {
            entity.totalPower = DateUtils.differentDaysDoubleByMillisecond(entity.getStartTime(), entity.getEndTime()) * 24 * entity.getNum() * entity.power;
        } catch (Exception e) {
            entity.totalPower = 0.;
            entity.setPid(entity.getWorkflowPaintHouseEntity().getId());
        }
        return entity;
    }
}
